package com.wagn.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wagn.oss.service.OssService;
import com.wagn.oss.utils.OssConfig;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadAvatar(MultipartFile file) {

        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = OssConfig.END_POINT;
        String accessKeyId = OssConfig.KEY_ID;
        String accessKeySecret = OssConfig.KEY_SECRET;
        String buketName = OssConfig.BUCKET_NAME;



        try{
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String objName = file.getOriginalFilename();
            objName = UUID.randomUUID().toString().replaceAll("-","")+objName;
            objName = new DateTime().toString("yyyy/MM/dd/")+objName;
            ossClient.putObject(buketName, objName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://wagn-edu.oss-cn-hangzhou.aliyuncs.com/201612150145225hrcae5abmu325412.jpg";
            url = "https://"+buketName+"."+endpoint+"/"+objName;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
